from asgiref.sync import sync_to_async
from django.contrib.auth import get_user_model
from rest_framework_simplejwt.tokens import AccessToken

User = get_user_model()  # 获取用户模型


async def async_get_user_from_token(token):
    try:
        access_token = AccessToken(token)
        print(access_token.payload)
        user_id = access_token['user_id']
        return await sync_to_async(User.objects.get)(user_id=user_id)
    except Exception as e:
        print(f"Token error: {e}")
        return None


def get_user_from_token(token):
    try:
        access_token = AccessToken(token)
        user_id = access_token['user_id']
        return User.objects.get(user_id=user_id)
    except Exception as e:
        print(f"Token error: {e}")
        return None


